import React, { useRef, useEffect, useState } from 'react';
import { Form, Button, Select, Modal, notification, AsyncButton } from '@block/plug';
import { $fetch } from '@block/utils';
import { TableRow, PersonSelectType, InterfacePersonDetail } from '../../types';
import Url from '../../url';
import './interfaceModel.scss';

const POP_LAYER = {
  getContainer: (): HTMLElement => document.querySelector('.interface-model') || document.body,
};

/** Props 声明 */
interface Props {
  /** 关闭侧滑方法 */
  onClose: () => void;
  /** 表格行数据 */
  row: TableRow;
}

/**
 * 新建 & 编辑接口人弹框
 */
const InterfaceModel = (props: Props) => {
  const { onClose, row } = props;

  /** state 定义 */
  const [interfacePersonTypeKey, setInterfacePersonTypeKey] = useState(null); // 接口人类型

  /** ref 定义 */
  const formRef = useRef(null);

  /** 取消按钮处理 */
  const handleClose = () => {
    onClose();
  };

  /** 获取弹窗接口人信息数据 */
  const handleGetInfo = async () => {
    const res = await $fetch<InterfacePersonDetail>(Url.viewInterfacePerson, {
      interfacePersonId: row?.interfacePersonId,
    });
    formRef?.current?.setAllFieldsValue(res);
    setInterfacePersonTypeKey(res.interfacePersonType);
  };

  /** didMount */
  useEffect(() => {
    handleGetInfo();
  }, []);

  /** 确认按钮处理 */
  const handleOk = async (_e: Event, btn: Button) => {
    const formData = formRef.current.getFieldsValue();
    const isEdit = Boolean(row?.interfacePersonId);
    const isPrivilegeOrgIdListNull = [
      PersonSelectType.SenPosOperations,
      PersonSelectType.SenPosOperationsLeader,
      PersonSelectType.ErLeader,
    ].includes(formData?.interfacePersonType);
    if (formRef.current.validateFields()) {
      try {
        btn.loading(true);
        const params = {
          interfacePersonId: isEdit ? row.interfacePersonId : undefined,
          empId: isEdit ? undefined : formData.interfacePersonEmpId,
          interfacePersonType: formData.interfacePersonType,
          privilegeOrgIdList: isPrivilegeOrgIdListNull
            ? null
            : formData.orgInfoList?.map((org: SelectOption) => org?.code),
        };
        const resData = isEdit
          ? await $fetch(Url.modifyInterfacePerson, params)
          : await $fetch(Url.addInterfacePerson, params);
        notification.success({ title: '成功', message: resData?.message || (isEdit ? '编辑成功' : '新建成功') });
        onClose();
      } finally {
        btn.loading(false);
      }
    }
  };

  /**
   * Form值变化处理
   * @param key 变化的key
   * @param value 变化的value
   */
  const handleOnFieldValueChange = (key: string, value) => {
    if (key === 'interfacePersonType') {
      setInterfacePersonTypeKey(value);
      if (
        [
          PersonSelectType.SenPosOperations,
          PersonSelectType.SenPosOperationsLeader,
          PersonSelectType.ErLeader,
        ].includes(value)
      ) {
        formRef.current.setFieldsValue({ orgInfoList: null });
      }
    }
  };

  return (
    <Modal
      className="interface-model"
      maskClosable={false}
      onClose={handleClose}
      title={`${row?.interfacePersonId ? '编辑' : '新建'}接口人`}
    >
      <Modal.Body>
        <Form ref={formRef} labelWidth="8em" onFieldValueChange={handleOnFieldValueChange}>
          <Form.Item
            formItemKey="interfacePersonEmpId"
            labelInValue={false}
            formItemLabel="interfacePersonEmpName"
            mode={row?.interfacePersonId ? 'disabled' : 'edit'}
            label="接口人："
            required
            message="姓名/MIS号不能为空"
          >
            <Select
              toFormItem
              keyField="code"
              labelField="name"
              popLayer={POP_LAYER}
              filterable
              onFetchData={(search: string) =>
                $fetch<SelectOption<string[]>>(Url.queryEmployeeList, { search: search?.trim() || ' ' })
              }
              placeholder="请输入姓名/MIS号"
              dispatchFetchDataWithoutKeyword={false}
            />
          </Form.Item>
          <Form.Item
            formItemKey="interfacePersonType"
            labelInValue={false}
            label="接口人类型："
            required
            message="接口人类型不能为空"
          >
            <Select
              toFormItem
              popLayer={POP_LAYER}
              keyField="code"
              labelField="name"
              filterable={false}
              onFetchData={() => $fetch<SelectOption<string[]>>(Url.queryInterfacePersonTypeList)}
              placeholder="请选择接口人类型"
            />
          </Form.Item>
          <Form.Item
            formItemKey="orgInfoList"
            label="适用组织："
            required={
              ![
                PersonSelectType.SenPosOperations,
                PersonSelectType.SenPosOperationsLeader,
                PersonSelectType.ErLeader,
              ].includes(interfacePersonTypeKey)
            }
            message="适用组织不能为空"
          >
            <Select
              toFormItem
              multiple
              popLayer={POP_LAYER}
              maxTagCount={5}
              keyField="code"
              labelField="name"
              disabled={[
                PersonSelectType.SenPosOperations,
                PersonSelectType.SenPosOperationsLeader,
                PersonSelectType.ErLeader,
              ].includes(interfacePersonTypeKey)}
              onFetchData={(search: string) =>
                $fetch<SelectOption<string[]>>(Url.queryOrgList, { search: search?.trim() || ' ' })
              }
              placeholder="请选择适用组织"
            />
          </Form.Item>
        </Form>
      </Modal.Body>
      <Modal.Footer>
        <Button style={{ marginRight: '12px' }} onClick={handleClose}>
          取消
        </Button>
        <AsyncButton type="primary" onClick={handleOk}>
          确定
        </AsyncButton>
      </Modal.Footer>
    </Modal>
  );
};
export default InterfaceModel;
